const Router = require("@koa/router");
const { ArticleModel } = require("../database/index");
const { Op } = require("sequelize")
const { where } = require("sequelize");
const router = new Router();

//添加文章信息
router.post("/addArticle",async(ctx,next)=>{
        const {title,desc,categeory,author,content,user_id} = ctx.request.body;
        console.log(111,title,desc,categeory,author,content)    
        try{

            const result  = await ArticleModel.create({
                title,
                desc,
                categeory,
                author,
                content,
                user_id,
            });
                console.log(result.toJSON());
                ctx.body = {
                    code:200,
                    msg:"添加成功"
                };
         }catch (error) {  
            console.error('Error adding article:', error); // 打印错误信息  
            ctx.body = {  
                code1: 500,  
                msg: "添加失败",  
                error: error.message || 'Unknown error' // 可选：提供更具体的错误消息  
            };  
        }});

//上传图片
router.post("/upload-img",async function(ctx,next){
    let imgLinks = []
    for(let i = 0;i < ctx.files.length; i++){
        let item = ctx.files[i]
        imgLinks.push({url:"http://"+ctx.request.host + "/img/" +item.filename,alt:item.filename});
    }
    ctx.body = {
        "errno":0,
        "data":imgLinks
    };
});

//获取文章信息
router.get('/getAllArticleByPage', async (ctx, next) => {
    const { categeory, title, currentPage, pageSize } = ctx.query;
    const condition1 = title ? { title: { [Op.like]: `%${title}%` } } : null;
    const condition2 = categeory ? { categeory: { [Op.eq]: categeory } } : null;

    const { count, rows } = await ArticleModel.findAndCountAll({
        where: Object.assign({}, condition1, condition2),

        offset: (currentPage - 1) * pageSize,
        limit: parseInt(pageSize)
    },)
    ctx.body = {
        code: 200,
        msg: "获取数据成功!!!",
        data: {
            rows: rows,
            count: count
        }
    };

});

//删除文章信息
router.post('/handleDelete', async (ctx, next) => {
    const { articleId } = ctx.request.body;
    try {
        const result = await ArticleModel.destroy({
            where: {
                articleId: articleId
            }
        });

        if (result) {
            ctx.body = {
                code: 200,
                msg: "删除成功"
            };
        } else {
            ctx.body = {
                code: 201,
                msg: "删除失败"
            };
        }
    } catch (error) {
        ctx.body = {
            code: 500,
            msg: "删除失败"
        };
    }
});

router.post("/updateArticle",async (ctx,next)=>{
    const {articleId,title,desc,categeory,author,content} = ctx.request.body;
    console.log("请求体内容", ctx.request.body);
    console.log("测试",title,desc,categeory,author,content);
    try{
        const result = await ArticleModel.update(
            {title,desc,categeory,content},
            {where:{articleId:articleId}}
        );
        console.log(result);
        if (result) {
            ctx.body = {
                code: 200,
                msg: "更新成功",
            };
        } else {
            ctx.body = {
                code: 500,
                msg: "更新失败",
            };
        }
    }catch(error){
        console.log(error);
        ctx.body = {
            code: 501,
            msg:"更新失败",
        };
    }
});
module.exports = router;

